package cn.newssdk.share;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.stonesun.android.MAgent;
import com.stonesun.newssdk.NewsAgent;
import com.stonesun.newssdk.sharesdk.NewsSDKShare;
import com.stonesun.newssdk.tools.TLog;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.favorite.WechatFavorite;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by  王子中 on 2017/11/15 0015.
 */

public class Share extends NewsSDKShare {
    JSONObject jsonObject;
    private String title;
    private String url;
    private String imageUrl;
    private String spot;
    private String item_id;
    private String set;
    private String mid;
    private String ad;
    private JSONObject reqJson;

    public Share() {
    }

    public  void showShare(String a, final Context ctx) {
        TLog.log("ttt showShare...........=="+a);
        try {
            JSONObject jsonObject=new JSONObject(a);
            if(jsonObject.has("type")){
                ad = jsonObject.getString("type");
                title = jsonObject.getString("title");
                url = jsonObject.getString("url");
                imageUrl = jsonObject.getString("_IMAGES");
            }else {
                TLog.log("ttt 没有type字段");
                spot = jsonObject.getString("spot");
                item_id = jsonObject.getString("item_id");
                set = jsonObject.getString("set");
                mid = jsonObject.getString("mid");
                imageUrl = jsonObject.getString("_IMAGES");
                url = jsonObject.getString("url");
                title = jsonObject.getString("title");
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(!"ad".equals(ad)){
            reqJson = new JSONObject();
            try {
                reqJson.put("item",item_id ); //内容唯一标识
                reqJson.put("spot", spot); //资讯位唯一标识

                reqJson.put("sapp", ""); //分享到的应用，wx,sina,weibo,qq
                reqJson.put("stype", ""); //分享方式 friend,group,circle
                reqJson.put("status", ""); //分享状态，0失败／1成功

                reqJson.put("set", set);//推荐集id
                reqJson.put("s", "");//搜索类型
                reqJson.put("q", "");//搜索语句
                reqJson.put("mid", mid);//菜单id
                reqJson.put("sdkv","android_"+ NewsAgent.getLibv());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        OnekeyShare oks = new OnekeyShare();
        // 参考代码配置章节，设置分享参数
        // 构造一个图标
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不     调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(title);
        TLog.log("ttt APP title！"+title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url+"&fsdk=1");
        TLog.log("ttt APP setTitleUrl！"+url+"&fsdk=1");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("来自{N}黑牛资讯的分享");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        if (TextUtils.isEmpty(imageUrl) || imageUrl.length() <= 0) {
            TLog.log("ttt APP imagesUrl= is null！");
            oks.setImageUrl("http://f1.sdk.mob.com/web/images/97f/fcb/1e73986a2fb559bbff6a02bec1.png");//确保SDcard下面存在此张图片
        } else {
            // 处理多张图片的场景
            /*String[] images = imageUrl.split("\\|");
            String shareImage = "";
            if (images.length > 0) {
                shareImage = images[0];
            }
*/          if(imageUrl.contains(",")){
                String[] split = imageUrl.split(",");
                String shareImage="";
                String imageUrls="";
                shareImage=split[0];
                imageUrls=shareImage.substring(2,shareImage.length()-1);
                TLog.log("ttt APP images.length=" + split.length);
                TLog.log("ttt APP imageUrl=" + imageUrls);
                oks.setImageUrl(imageUrls);//确保SDcard下面存在此张图片
            }else {
                String imageUrls="";
                imageUrls=imageUrl.substring(2,imageUrl.length()-2);
                TLog.log("ttt APP imageUrl=" + imageUrls);
                oks.setImageUrl(imageUrls);//确保SDcard下面存在此张图片
            }
           /* String[] split = imageUrl.split(",");
            String shareImage="";
            String imageUrls="";
            if(split.length>1){
                shareImage=split[0];
                imageUrls=shareImage.substring(2,shareImage.length()-1);
            }else {
                imageUrls=shareImage.substring(2,shareImage.length()-1);
            }
            TLog.log("ttt APP images.length=" + split.length);
            TLog.log("ttt APP imageUrl=" + imageUrls);
            oks.setImageUrl(imageUrls);//确保SDcard下面存在此张图片*/
        }
        //通过OneKeyShareCallback来修改不同平台分享的内容
        //自定义平台可以通过判断不同的平台来实现不同平台间的不同操作
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            //自定义分享的回调想要函数
            @Override
            public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
                TLog.log("ttt APP paramsToShare=" + paramsToShare);
                TLog.log("ttt APP platform.getName()=" + platform.getName());
                if(!"ad".equals(ad)){
                    try {
                        if (QZone.NAME.equals(platform.getName())) {
                            reqJson.put("sapp","qq"); //分享到的应用，wx,sina,weibo,qq
                            reqJson.put("stype","qzone"); //分享方式 friend,group,circle
                        }else if(QQ.NAME.equals(platform.getName())){
                            reqJson.put("sapp","qq"); //分享到的应用，wx,sina,weibo,qq
                            reqJson.put("stype","firend"); //分享方式 friend,group,circle

                        }else if(SinaWeibo.NAME.equals(platform.getName())){
                            reqJson.put("sapp","sina"); //分享到的应用，wx,sina,weibo,qq
                            reqJson.put("stype","weibo"); //分享方式 friend,group,circle

                        }else if(Wechat.NAME.equals(platform.getName())){
                            reqJson.put("sapp","wx"); //分享到的应用，wx,sina,weibo,qq
                            reqJson.put("stype","firend"); //分享方式 friend,group,circle
                        }else if(WechatMoments.NAME.equals(platform.getName())){
                            reqJson.put("sapp","wx"); //分享到的应用，wx,sina,weibo,qq
                            reqJson.put("stype","timeline"); //分享方式 friend,group,circle
                        }else if(WechatFavorite.NAME.equals(platform.getName())){
                            reqJson.put("sapp","wx"); //分享到的应用，wx,sina,weibo,qq
                            reqJson.put("stype","wxcollection"); //分享方式 friend,group,circle
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                //点击收藏
                if (QZone.NAME.equals(platform.getName())) {
                    TLog.log("ttt APP qq回调");
                }

                //点击分享发送行为
                onBeginShare(reqJson,ctx);
            }
        });

        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url+"&fsdk=1");
        TLog.log("ttt setUrl"+url+"&fsdk=1");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("来自{N}黑牛资讯的分享");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("NewsSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url+"&fsdk=1");
        TLog.log("ttt setSiteUrl"+url+"&fsdk=1");

        oks.setCallback(new PlatformActionListener() {

            @Override
            public void onComplete(Platform patform, int i, HashMap<String, Object> hashMap) {
                TLog.log("分享成功~~~" );
                Toast.makeText(ctx,"操作成功", Toast.LENGTH_SHORT).show();
                try {
                    reqJson.put("status", 1); //分享状态，0失败／1成功
                    String req = reqJson.toString();
                    TLog.log("req=====" + req);
                    //MAgent.onShareEvent(ctx, "share", req);
                    MAgent.onRecommCliEvent(ctx, "share", "Recomm_share", req.toString());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Toast.makeText(ctx,"分享失败", Toast.LENGTH_SHORT).show();
                TLog.log("分享失败~~~" );
                Log.e("TAG","throwable==="+throwable);
                if (!"ad".equals(ad)){
                    try {
                        reqJson.put("status", 0); //分享状态，0失败／1成功
                        String req = reqJson.toString();
                        TLog.log("req=====" + req);
                        //MAgent.onShareEvent(ctx, "share", req);
                        MAgent.onRecommCliEvent(ctx, "share", "Recomm_share", req.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            @Override
            public void onCancel(Platform platform, int i) {
                Toast.makeText(ctx,"分享取消", Toast.LENGTH_SHORT).show();
                TLog.log("分享取消~~~" );
                if(!"ad".equals(ad)){
                    try {
                        reqJson.put("status", 3); //分享状态，0失败／1成功
                        String req = reqJson.toString();
                        TLog.log("req=====" + req);
                        //MAgent.onShareEvent(ctx, "share", req);
                        MAgent.onRecommCliEvent(ctx, "share", "Recomm_share", req.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        // 启动分享GUI
        oks.show(ctx);
    }

    private void onBeginShare(JSONObject reqJson, Context ctx) {
        Toast.makeText(ctx,"分享开始", Toast.LENGTH_SHORT).show();
        TLog.log("分享开始~~~" );
        if(!"ad".equals(ad)){
            try {
                reqJson.put("status", 0); //开始分享
                String req = reqJson.toString();
                TLog.log("req=====" + req);
                //MAgent.onShareEvent(ctx, "share", req);
                MAgent.onRecommCliEvent(ctx, "share", "Recomm_share", req.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
